#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <semaphore>


// 模拟资源池的大小
const int MAX_RESOURCES = 9;

// 创建一个计数信号量，初始可用资源数为 MAX_RESOURCES
std::counting_semaphore resource_semaphore(MAX_RESOURCES);

// 一个模拟任务使用资源的函数
void use_resource(int id, int num_resources) {
    try {
        // 尝试获取指定数量的资源
        for (int i = 0; i < num_resources; ++i) {
            resource_semaphore.acquire();
        }
        std::cout << "Thread " << id << " acquired " << num_resources << " resources." << std::endl;

        // 模拟执行一些工作
        std::this_thread::sleep_for(std::chrono::seconds(1));

        // 释放资源
        for (int i = 0; i < num_resources; ++i) {
            resource_semaphore.release();
        }
        std::cout << "Thread " << id << " released " << num_resources << " resources." << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Thread " << id << " encountered an exception: " << e.what() << std::endl;
    }
}

int main() {
    std::vector<std::thread> threads;

    // 启动多个线程来模拟并发请求
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(use_resource, i, i + 1); // 请求资源数量逐渐增加
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    return 0;
}